# -*- coding: utf-8 -*-
import re
from datetime import datetime
from bs4 import BeautifulSoup
import sys
from app import db
from app.metapage_parser import get_iframe_link, get_iframe_content
from app.models import Dionica
from app.page_manager import get_web_page, get_link_in_div, clean_text, get_content_in_div_like

# Naslovna stranica sa svim dionicama
main_page = 'http://icapital.hr/stocks/overview/VW04PQ=='

#Globalne varijable
linkovi = []
tablica = {}

def get_dionice_links():
    #Prvo pokupim cijeli sajt sa tickerima
    main_page_data = get_web_page(main_page)
    linkovi = get_link_in_div(main_page_data, 'ticker')
    return linkovi

def get_dionica_name(text):
    if text is not None:
        soup = BeautifulSoup(text)

        data = soup.find('div', {'class' : 'fund_name'})
        if data is not None:
            data = data.text
        else:
            data = "NaN"
        return  data

def clean_dionice():
    db.session.clear_collection(Dionica)

def create_dionica_from_link(link):
    dionice = []

    data = get_web_page(link)
    # Naslov dionice
    dioniNaslov = get_dionica_name(data)
    dioniNaslov = dioniNaslov.replace('\n','').rstrip().lstrip()

    # Dohvacamo sadrzaj svih vjesti
    vijesti = get_content_in_div_like(data, 'stock_news_item')

    countVijesti = 0
    countVijesti = len(vijesti)
    for i, vijest in enumerate(vijesti):
        print "Vijest " , i, " od ", countVijesti
        if i is 1:
            print("stani")

        # Vrijeme vijesti
        news_date = vijest.find('div', {'class' : 'date'})
        if news_date is not None:
            news_date = news_date.text
            datum = re.search(r'\d{1,2}.\d{1,2}.\d{4} \d{1,2}:\d{1,2}:\d{1,2}', news_date)
        else:
            datum = datetime.now().strftime('%d.%m.%Y')
        # print(datum.group())
        date_object = datetime.strptime(datum.group(), '%d.%m.%Y %H:%M:%S')

        # Sentiment
        sentiment = vijest.find('div', {'class' : 'orientation'})
        if sentiment is not None:
            sentiment = sentiment.text
            sentiment = sentiment.replace("N", "Neutralna")
            sentiment = sentiment.replace("+", "Pozitivna")
            sentiment = sentiment.replace("-", "Negativna")
        else:
            sentiment = "NaN"
        # print(sentiment)

        # Naslov
        naslov = vijest.find('div', {'class' : 'heading'})
        if naslov is not None:
            naslov = naslov.text
            naslov = clean_text(naslov)
        else:
            naslov = "NaN"
        # print(naslov)

        # Meta
        meta = vijest.find('div', {'class' : 'meta'})
        if meta is not None:
            meta = meta.text
            # link
            fullTextLink = vijest.find('a', {'target' : '_blank'})['href']

            iframeLink = get_iframe_link(fullTextLink)
            content = get_iframe_content(iframeLink, meta)
            if content is not None:
                content = clean_text(content)
            else:
                content = "NaN"
        else:
            meta = "NaN"

        # Sadrzaj
        sadrzaj = vijest.find(True, {'class' : re.compile('body')})
        if sadrzaj is not None:
            sadrzaj = sadrzaj.text
            sadrzaj = clean_text(sadrzaj)
        else:
            sadrzaj = "NaN"
        # print(sadrzaj)

        dionica = None
        try:
            dionica = Dionica(dionicaName=dioniNaslov, news_date=date_object,
                              sentiment=sentiment, header=naslov, short_content=sadrzaj,
                              content=content)
        except:
            print "Unexpected error:", sys.exc_info()[0]

        dionice.append(dionica)
    return dionice

def update_dionice():
    linkovi = get_dionice_links()

    #Setam counter za broj dionica koji ce obradivati
    #Kako bi lakse pratio u debugu status
    #TODO: Sloziti progress bar
    dioniceCount = 0
    dioniceCount = len(linkovi)

    # Krecem po svim linkovima koji sam nasao
    for i, link in enumerate(linkovi):
            print i, " od  ",  dioniceCount

            item = db.session.query(Dionica).filter(Dionica.dionicaName == link.name).first()
            if item is None:
                dionice = create_dionica_from_link(link.link)

                for dionica in dionice:
                    db.session.save(dionica)

def clean_refresh_dionice():
    #Clean dionice
    clean_dionice()

    linkovi = get_dionice_links()

    #Setam counter za broj dionica koji ce obradivati
    #Kako bi lakse pratio u debugu status
    #TODO: Sloziti progress bar
    dioniceCount = 0
    dioniceCount = len(linkovi)

    # Krecem po svim linkovima koji sam nasao
    for i, link in enumerate(linkovi):
            print i, " od  ",  dioniceCount
            dionice = create_dionica_from_link(link.link)

            for dionica in dionice:
                db.session.save(dionica)